<template>
  <div class="container page-component__scroll">
    <!-- <canvas id="canvas"></canvas> -->
    <Nav :isLogin="isLogin" :selfUserInfo="selfUserInfo"></Nav>
    <div
      class="global-nav-bottom"
      :class="isShowNav ? 'global-nav-bottom-hide' : ''"
    >
      <ul>
        <li
          :class="item.active ? 'changeActive' : ''"
          v-for="(item, index) in navBotList"
          :key="index"
          @click="chooseItem(index)"
        >
          {{ item.articleName }}
        </li>
      </ul>
    </div>
    <div class="mainContent">
      <div class="main-left">
        <div class="fullter">
          <ul>
            <li
              :class="currentIndex == index ? 'active' : ''"
              @click="switchHotType(index)"
              v-for="(item, index) in maxType"
              :key="index"
            >
              {{ item.type }}
            </li>
          </ul>
        </div>
        <keep-alive>
          <ArticItem :articItem="articItem" @toPreview="toPreview"></ArticItem>
        </keep-alive>
      </div>
      <div class="main-right">
        <div class="login" v-if="!isLogin">
          <div class="login-title">掘金 - juejin.cn</div>
          <div class="login-desc">一个帮助开发者成长的社区</div>
          <div class="login-input">
            <div>+86</div>
            <input
              type="text"
              placeholder="请输入手机号"
              maxlength="11"
              v-model="phoneNumber"
            />
          </div>
          <div class="login-code">
            <input
              type="text"
              placeholder="验证码"
              v-model="codeNumber"
              maxlength="4"
            />
            <div
              @click="getPhoneCode"
              :class="timeScode == 60 ? 'isSendSty' : 'stopSendSty'"
            >
              {{ loginText }}
            </div>
          </div>
          <div class="login-btn" @click="loginPhone">立即登录</div>
          <div class="login-bot">
            注册登录即表示同意 <span>用户协议</span>、<span>隐私政策</span>
          </div>
        </div>
        <div
          v-for="(item, index) in this.bannerList"
          :key="index"
          @click="toBannerDetail(item.id)"
        >
          <img v-if="index < 2" class="bannerImg" :src="item.articleImg" />
        </div>

        <!-- 下载掘金客户端 -->
        <DownloadClient />
        <Child />
        <!-- 作者榜 -->
        <ArticleRankingList />

        <div class="otherSource">
          <div class="sourceItem" v-for="i in 3" :key="i">
            <img
              src="//sf3-scmcdn2-tos.pstatp.com/xitu_juejin_web/img/juejin-tutu.d58819c.png"
              alt=""
            />
            <span>掘金社区漫游指南</span>
          </div>
        </div>
      </div>
    </div>
    <!-- <div class="mask"></div> -->
    <div class="validatorSty" id="validatorSty" v-if="showvalidator">
      <div id="captcha">
        <div id="handle">
          <span @mousedown="mouseDown($event)"></span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ArticleRankingList from "@component/Article/ArticleRankingList.vue"
import DownloadClient from "@component/Article/DownloadClient.vue"
import ArticItem from "@component/Article/ArticleItem.vue"
import Nav from "@component/Nav.vue"
import Child from "@component/Child.vue"
import { mapState } from "vuex"
export default {
  components: {
    ArticItem,
    Nav,
    ArticleRankingList,
    DownloadClient,
    Child,
  },
  computed: {
    ...mapState(["isShowNav"]),
  },
  data() {
    return {
      navBotList: [],
      isHideNavBot: false,
      page: 1,
      blackCode: "2575",
      loginText: "获取验证码",
      articItem: [],
      isLogin: false,
      bannerList: [],
      codeNumber: "",
      moveObject: {
        xx: 0,
      },
      finallBankList: {
        left: 80,
        top: 80,
        bottom: 20,
        height: 72,
        width: 72,
      },
      showvalidator: false,
      isMove: false,
      timeScode: 60,
      timerID: null,

      currentIndex: 0,
      queryList: {
        page: 1,
      },
      selfUserInfo: {},
      phoneNumber: "",
      maxType: [
        {
          type: "热门",
          id: 1,
        },
        {
          type: "最新",
          id: 2,
        },
        {
          type: "热榜",
          id: 3,
        },
      ],
      backgroundObj: {
        aw: 0,
        ah: 0,
        ctx: null,
        x: 0,
        y: 0,
        r: 3,
        speedX: Math.random() * 3 * Math.pow(-1, Math.round(Math.random())),
        speedY: Math.random() * 3 * Math.pow(-1, Math.round(Math.random())),
      },
    }
  },
  created() {
    this.getArticleType()
    this.getArticleList()
    // this.getBannerList()
    this.backgroundObj.aw =
      document.documentElement.clientWidth || document.body.clientWidth
    this.backgroundObj.ah =
      document.documentElement.clientHeight || document.body.clientHeight
    let userInfo = window.localStorage.getItem("userInfo")
    if (userInfo) {
      this.selfUserInfo = JSON.parse(userInfo)
      this.isLogin = true
    }
  },
  destroyed() {
    document.removeEventListener("scroll", this.listenerFunction)
  },
  mounted() {
    // 获取当前视图的宽度和高度
    // this.getBackground()

    this.listenerFunction()
  },
  methods: {
    listenerFunction(e) {
      document.addEventListener("scroll", this.handleScroll, true)
    },
    handleScroll() {
      // 变量scrollTop是滚动条滚动时，距离顶部的距离
      var scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
      if (scrollTop > 500) {
        this.$store.state.isShowNav = true
      } else {
        this.$store.state.isShowNav = false
      }
      // 变量windowHeight是可视区的高度
      var windowHeight =
        document.documentElement.clientHeight || document.body.clientHeight
      // 变量scrollHeight是滚动条的总高度
      var scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight
      // 滚动条到底部的条件
      if (Math.ceil(scrollTop) + windowHeight === scrollHeight) {
        // 到了这个就可以进行业务逻辑加载后台数据了
        console.log("到了底部到了底部到了底部到了底部到了底部到了底部")
      }
    },
    async toPreview(data) {
      await this.getUserInfo(data)
      this.$router.push({
        path: "/previewArticle",
        query: { contentId: data.id },
      })
    },
    async getUserInfo(data) {
      const { data: res } = await this.$http.post("/user/userInfo", {
        userId: data.userId,
      })
      if (res.status === "SUCCESS" && res.result.length) {
        window.localStorage.setItem(
          "otherUserInfo",
          JSON.stringify(res.result[0])
        )
        return true
      }
      return false
    },
    getBackground() {
      const canvas = document.getElementById("canvas")
      canvas.width = this.backgroundObj.aw
      canvas.height = this.backgroundObj.ah

      this.backgroundObj.ctx = canvas.getContext("2d")
      // 本游戏无论是实心，还是线条，色调都是白色
      this.backgroundObj.ctx.fillStyle = "white"
      this.backgroundObj.ctx.strokeStyle = "white"
      // 星星的移动
      // const start = new Star(Math.random() * this.backgroundObj.aw, Math.random() * this.backgroundObj.aw, 3)
      // console.log(start);
      // const stars = []
      // for (let i = 0; i < 100; i++) {
      //     // 随机在canvas范围内找一个坐标画星星
      //     let obj = {
      //       x: Math.random() * this.backgroundObj.aw,
      //       y: Math.random() * this.backgroundObj.ah,
      //       r: 3
      //     }
      //     stars.push(obj)
      // }
      // clearInterval(this.backgroundObj.timeId)
      // this.backgroundObj.timeId = setInterval(() => {
      //     this.backgroundObj.ctx.clearRect(0, 0, this.backgroundObj.aw, this.backgroundObj.ah)
      //     // 遍历移动渲染
      //     stars.forEach(star => {
      //         this.move()
      //         this.draw()
      //     })
      //     stars.forEach((star, index) => {
      //         // 类似于冒泡排序那样，去比较，确保所有星星两两之间都比较到
      //         for (let i = index + 1; i < stars.length; i++) {
      //             if (Math.abs(star.x - stars[i].x) < 50 && Math.abs(star.y - stars[i].y) < 50) {
      //                 this.drawLine(star.x, star.y, stars[i].x, stars[i].y)
      //             }
      //         }
      //         // if (Math.abs(mouseStar.x - star.x) < 50 && Math.abs(mouseStar.y - star.y) < 50) {
      //         //     this.drawLine(mouseStar.x, mouseStar.y, star.x, star.y)
      //         // }
      //     })
      // }, 50)
    },
    drawLine(startX, startY, endX, endY) {
      this.backgroundObj.ctx.beginPath()
      this.backgroundObj.ctx.moveTo(startX, startY)
      this.backgroundObj.ctx.lineTo(endX, endY)
      this.backgroundObj.ctx.stroke()
      this.backgroundObj.ctx.closePath()
    },
    draw() {
      this.backgroundObj.ctx.beginPath()
      this.backgroundObj.ctx.arc(
        this.backgroundObj.x,
        this.backgroundObj.y,
        this.backgroundObj.r,
        0,
        Math.PI * 2
      )
      this.backgroundObj.ctx.fill()
      this.backgroundObj.ctx.closePath()
    },
    move() {
      this.backgroundObj.x -= this.backgroundObj.speedX
      this.backgroundObj.y -= this.backgroundObj.speedY
      // 碰到边界时，反弹，只需要把speed取反就行
      if (
        this.backgroundObj.x < 0 ||
        this.backgroundObj.x > this.backgroundObj.aw
      )
        this.backgroundObj.speedX *= -1
      if (
        this.backgroundObj.y < 0 ||
        this.backgroundObj.y > this.backgroundObj.ah
      )
        this.backgroundObj.speedY *= -1
    },
    async getArticleType() {
      const { data: res } = await this.$http.get("/article/articleType")
      if (res.msg === "SUCCESS") {
        this.navBotList = res.result
        this.navBotList.unshift({
          articleName: "推荐",
          status: false,
          active: true,
        })
        // console.log(res.result)
      }
    },
    async getArticleList() {
      const { data: res } = await this.$http.get("/article/articlelist", {
        params: this.queryList,
      })
      if (this.page === 1) {
        this.articItem = []
      }
      if (res.result.length > 0) {
        res.result.map((item, index) => {
          item.updatedAt = this.$utils.timeRight(item.updatedAt)
        })
        this.articItem = Object.assign([], res.result)
      }
    },
    async getBannerList() {
      const { data: res } = await this.$http.get("bannerList")
      if (res.msg === "SUCCESS") {
        res.result.map((item, index) => {
          item.articleImg = this.$formatImg + item.articleImg
        })

        this.bannerList = res.result
      }
    },
    mouseDown(event) {
      const captcha = document.querySelector("#captcha")
      const handle = document.querySelector("#handle")
      const button = document.querySelector("#handle span")
      this.isMove = true
      window.addEventListener("mousemove", (e) => {
        if (this.isMove) {
          const offsetLeft = handle.getBoundingClientRect().left
          const buttonWidth = button.getBoundingClientRect().width
          captcha.style.setProperty(
            "--moved",
            `${e.clientX - offsetLeft - buttonWidth / 2}px`
          )
        }
      })
      window.addEventListener("mouseup", (e) => {
        this.mouseUp(e, captcha, handle, button)
      })
    },
    async mouseUp(e, captcha, handle1, button) {
      if (this.isMove) {
        const finalOffset = e.clientX - handle1.getBoundingClientRect().left
        console.log(`finalOffset`, finalOffset)
        if (finalOffset >= 430 && finalOffset <= 450) {
          console.log("验证成功")
          captcha.classList.add("passed")
          this.closeValidator()
          const queryList = { phoneNumber: this.phoneNumber }
          const { data: res } = await this.$http.get("user/sendSMS", {
            params: queryList,
          })
          if (res.status === "SUCCESS") {
            this.timerID = setInterval(() => {
              this.getScode(this.timerID)
            }, 1000)
            this.blackCode = res.result
          }
        } else {
          captcha.style.setProperty("--moved", "0px")
          console.log("验证失败")
        }

        this.isMove = false
      }
    },
    getScode() {
      if (this.timeScode === 0) {
        this.loginText = "发送验证码"
        this.timeScode = 60
        clearInterval(this.timerID)
      } else {
        this.timeScode--
        this.loginText = this.timeScode + "后重新发送短信"
      }
    },
    mouseMove(e) {
      if (this.isMove) {
        const offsetLeft = this.handle.getBoundingClientRect().left
        const buttonWidth = this.handlebutton.getBoundingClientRect().width
        this.captcha.style.setProperty(
          "--moved",
          `${e.clientX - offsetLeft - buttonWidth / 2}px`
        )
      }
    },
    validator() {},
    toBannerDetail(id) {
      console.log(id)
    },

    closeValidator() {
      this.isMove = false
      this.showvalidator = false
    },
    switchHotType(ind) {
      this.currentIndex = ind
      this.queryList.hotTypeId = ind
      this.getArticleList()
    },
    chooseItem(ind) {
      this.navBotList.map((item, index) => {
        if (ind === index) {
          this.$set(item, "active", true)
          this.queryList.articleId = item.articleId
          this.getArticleList()
        } else {
          this.$set(item, "active", false)
        }
      })
    },
    refresh() {
      console.log(this.finallBankList.left)
      this.$forceUpdate()
    },
    async loginPhone() {
      if (this.phoneNumber === "") {
        alert("请输入手机号码")
        return
      }
      if (this.blackCode !== this.codeNumber) {
        alert("验证码错误")
        return true
      }

      if (this.blackCode === this.codeNumber) {
        let queryList = {
          phoneNumber: this.phoneNumber,
          codeNumber: this.codeNumber,
        }
        const { data: res } = await this.$http.get("user/phoneLogin", {
          params: queryList,
        })
        console.log(`res`, res)
        if (res.status === "SUCCESS") {
          this.$message.success("登录成功")
          localStorage.setItem("userInfo", JSON.stringify(res.result))
          localStorage.setItem("token", res.result.token)
          this.isLogin = true
          clearInterval(this.timerID)
        }
      }
    },
    async getPhoneCode() {
      if (this.timeScode !== 60) {
        return
      }
      if (!this.phoneNumber) {
        alert("请输入手机号码")
        return
      }

      if (this.$utils.getIsPhoneMobeil(this.phoneNumber)) {
        //手机格式不正确
        alert("请输入正确格式的手机号码")
        return
      }
      this.finallBankList.left =
        Math.floor(
          Math.random() *
            (336 -
              this.finallBankList.width -
              (168 - this.finallBankList.width / 2))
        ) +
        (168 - this.finallBankList.width / 2)
      this.finallBankList.top =
        Math.floor(Math.random() * (300 - this.finallBankList.height - 30)) + 30
      this.showvalidator = true
      console.log(`1232`, 1232)
    },
  },
}
</script>

<style lang="less" scoped>
@import "../assets/css/login.less";
@import "../assets/css/index.less";

li {
  cursor: pointer;
  list-style: none;
}
.container {
  margin-top: 11rem;
  height: 100%;
}
</style>
